<template>
  <el-dialog :model-value="dialogVisible" :title="dialogDatas.title" :destroy-on-close="true" @close="closeDialog">
    <div>
      <el-form style="height:180px;overflow: auto;" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" :disabled="dialogDatas?.type == 'check'">
        <el-form-item label="套餐名称" prop="mealName">
          <el-input v-model="ruleForm.mealName" placeholder="请输入套餐名称" clearable maxlength="20" />
        </el-form-item>
        <el-form-item label="使用点数" prop="points">
          <el-input v-model="ruleForm.points" placeholder="请输入使用点数" oninput="value=value.replace(/[^\d]/g,'')" clearable maxlength="10" />
        </el-form-item>
        <el-form-item label="套餐描述" prop="remark" class="is-required" >
          <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入套餐描述" maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <div v-if="showOrgs">
        <P class="w-full text-center mb6 mt2">包含检测项</P>
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" height="400px" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="50" v-if="!(dialogDatas?.type == 'check')" />
          <el-table-column type="index" width="80" label="sort" align="center" />
          <el-table-column property="id" label="ID" align="center" />
          <el-table-column property="projectId" label="Report ID" show-overflow-tooltip align="center" />
          <el-table-column property="type" label="Type" align="center" />
          <el-table-column property="title" label="Title" align="center" />
        </el-table>
      </div>
    </div>
    <template #footer v-if="!(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
      </span>
    </template>
    <template #footer v-if="(dialogDatas?.type == 'check')">
      <span class="dialog-footer" style="display: block;text-align: center;">
        <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onBeforeMount, toRefs ,nextTick} from 'vue';
import {
  mealaddRequest,
  MealDetailRequest,
  mealEditRequest,
  reportRequest
} from '@/api/system/meal/index';
import type { FormInstance, FormRules } from 'element-plus';
const emit = defineEmits(['updateList', 'changeCheck', 'update:dialogVisible']);
const visible = ref(false);
let showOrgs = ref(true)
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogDatas: {
    type: Object,
    default: () => { }
  }
});
const { dialogVisible, dialogDatas } = toRefs(props);
const ruleFormRef = ref<FormInstance>()
let multipleTableRef = ref()
let tableData = reactive([])
const ruleForm = reactive({
  id:null,
  mealName: null,
  points: null,
  remark: '',
  reportIds:[]
})

// 校验
const rules = reactive<FormRules>({
  mealName: [{ required: true, message: '请输入套餐名称', trigger: 'change' }],
  points: [{ required: true, message: '请输入使用点数', trigger: 'change' }],
  remark: [{ required: true, message: '请输入套餐描述', trigger: 'change' }],
})
const multipleSelection =ref([ ])
// 获取勾选数据
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
let toggleSelection = (rows: any) => {
  if (rows) {
    rows.forEach((row: any) => {
      if(row.isCheck){  //单个情况回显
        multipleTableRef.value!.toggleRowSelection(row, true) // 默认勾选
      } else {
        multipleTableRef.value!.toggleRowSelection(row, false) // 不选中
      }
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
// 获取检测项列表
const reportFun = async () => {
  showOrgs.value = false
  let data: any = await reportRequest({})
  let res = data.data
  tableData = res
  showOrgs.value = true
}
// const init = async (tableData: any) => {
//   if (tableData) dialogDatas.value = JSON.parse(JSON.stringify(tableData));
//   // multipleSelection.value = dialogDatas.value.datas.checkedColumn;
//   nextTick(() =>{
//     toggleSelection(dialogDatas.value.datas.tableData);
//   })
// };

//提交
const confirm = async (formEl: FormInstance | undefined) => {
  ruleForm.reportIds=(multipleSelection.value).map(obj => obj.id)
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let Url = dialogDatas.value.type == 'add' ? mealaddRequest : mealEditRequest;
      let res: any = await Url(ruleForm);
      if (res.code === 2000) {
        ElMessage.success('保存成功')
        emit("update:dialogVisible", false);
      } else {
        ElMessage.error(res.message)
      }
      formEl.resetFields()//重置
      emit('updateList')
    } else {
      console.log('保存失败', fields)
    }
  })
}

// 取消&重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  emit('updateList')
  emit("update:dialogVisible", false);
}
// 关闭
const closeDialog = () => {
  emit('updateList')
}

const getMealDetailFun = async () => {
  console.log(dialogDatas.value.datas,"dialogDatas.value.datas")
  const data: any = await MealDetailRequest({ mealId: dialogDatas.value.datas.id })
  let res = data.data;
  let newArray = []
  showOrgs.value = false
  if (dialogDatas.value.type ==='edit') {
    newArray = res.reportProjectResps;
    console.log(newArray,"newArray")
    nextTick(() =>{
      toggleSelection(newArray)
    })
    // dialogConfig1.checkedColumn = (newArray).filter((obj:any) => obj.isCheck === true);//选中的
  } else {
    newArray = (res.reportProjectResps).filter((obj:any) => obj.isCheck === true);
  }
  ruleForm.id = res.id
  ruleForm.mealName = res.mealName
  ruleForm.points = res.points
  ruleForm.remark = res.remark
  ruleForm.reportIds = res.reportIds
  console.log(ruleForm.reportIds,"reportIds")
  tableData = newArray;   //区分查看和编辑
  showOrgs.value = true
}

onBeforeMount(async () => {
  // reportFun()
  if (dialogDatas.value.type == 'add') {
    reportFun()
  } else {
    getMealDetailFun()
  }
})
// defineExpose({ init });
</script>

<style lang="scss" scoped>
.el-dialog__footer{
  text-align: center;
}
</style>
